package com.example.demo2.filter;

import org.apache.commons.lang3.StringUtils;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.GenericFilterBean;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Description:
 *
 * @author liuziyang
 * @date 2021/6/30 11:42
 */
@Component
public class VerifyCodeFilter extends GenericFilterBean {
    private final String defaultFilterProcessUrl = "/doLogin";

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request0 = (HttpServletRequest) request;
        HttpServletResponse response0 = (HttpServletResponse) response;
        if ("POST".equalsIgnoreCase(request0.getMethod()) && defaultFilterProcessUrl.equals(request0.getServletPath())) {
            // 验证码验证
            String requestCaptcha = request0.getParameter("code");
            String genCaptcha = (String) request0.getSession().getAttribute("index_code");
            if (StringUtils.isEmpty(requestCaptcha)) {
                throw new AuthenticationServiceException("验证码不能为空!");
            }
            if (!genCaptcha.equalsIgnoreCase(requestCaptcha)) {
                throw new AuthenticationServiceException("验证码错误!");
            }
        }
        chain.doFilter(request0, response0);
    }
}
